package com.photoeditor.demo.ui.widget.image.edit;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.app.ItemClickSupport;
import com.photoeditor.demo.app.XActivity;
import com.photoeditor.demo.model.bean.EmojiBean;
import com.photoeditor.demo.model.bean.EmojiPageBean;
import com.photoeditor.demo.model.bean.PagePositionBean;
import com.photoeditor.demo.model.image.emoji.InsideStickerTool;
import com.photoeditor.demo.model.image.emoji.LocalStickerData;
import com.photoeditor.demo.model.image.emoji.StickerApkResource;
import com.photoeditor.demo.model.image.emoji.StickerConstant;
import com.photoeditor.demo.model.image.emoji.StickerManager;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.adapter.stash.EmojiPageAdapter;
import com.photoeditor.demo.ui.widget.LineIndicator;
import com.photoeditor.demo.ui.widget.LoadingView;
import com.photoeditor.demo.ui.widget.RoundImageView;
import com.photoeditor.demo.ui.widget.image.emoji.EmojiCheckableItem;
import com.photoeditor.demo.ui.widget.image.emoji.EmojiItem;
import com.photoeditor.demo.ui.widget.image.emoji.StickerButtonAdapter;
import com.photoeditor.demo.ui.widget.stash.edit.StickerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class EmojiBarView extends LinearLayout implements IDealInit, EmojiPageAdapter.StickerBar {

    private RecyclerView mStickerButtonList;
    private StickerButtonAdapter mButtonAdapter;

    //包名是键 值是该包名第一页的Index  这个是按照插入顺序记录的  直接迭代就是插入顺序
    private LinkedHashMap<String, PagePositionBean> mIndexMap;

    private ArrayList<EmojiPageBean> mPageData;

    private View mEmojiPanelLayout;

    private ViewPager mEmojiPager;

    private LinearLayout mIndicatorLayout;

    private EmojiPageAdapter mPagerAdapter;

    private Animation mEmojiPanelIn;

    private Animation mEmojiPanelOut;

    private boolean mFinishInflate = false;

    private int mLastPosition = 0;

    private ProgressDialog mWaitProgressDialog;
    private AtomicInteger mDialogCount = new AtomicInteger(0);//用于控制Dialog正确展示

    private boolean mNeedRefresh = false;

    private AlertDialog mConfirmDialog;

    private XActivity mActivity;

    private StickerManager mManager;

    private boolean isLineIndicator;
    private LineIndicator mIndicator;
    private Bitmap mStickerBackground;

    private StickerIndicatorView mStickerIndicatorView;
    private LinearLayoutManager mLinearLayoutManager;

    private int mGifAutoScrollPosition = -1;
    private int mStickerAutoScrollPosition = -1;

    public void setStickerBackground(Bitmap stickerBackground) {
        mStickerBackground = stickerBackground;
    }

    private StickerView.StickerViewListener mStickerViewListener;

    public EmojiBarView(Context context) {
        this(context, null);
    }

    public EmojiBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mActivity = (XActivity) context;
        mIndexMap = new LinkedHashMap<String, PagePositionBean>();
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mFinishInflate = true;
        mStickerButtonList = (RecyclerView) this.findViewById(R.id.sticker_button_list);
        mLinearLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false);
        mStickerButtonList.setLayoutManager(mLinearLayoutManager);
        mStickerButtonList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mStickerIndicatorView.moveByDistance(-dx);
            }
        });
        findViewById(R.id.btn_sticker_more).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mStickerViewListener != null) {
                    mStickerViewListener.onMoreClick();
                }
            }
        });
        mStickerIndicatorView = (StickerIndicatorView) this.findViewById(R.id.sticker_indicator_view);
    }


    /**
     * 初始化EmojiView
     */
    @Override
    public void init() {
        if (!SPDataManager.hasUseSticker()) {
            setVisibility(GONE);
            SPDataManager.setHasUseSticker(true);
            return;
        }
        DLog.d("fLog", "EmojiBarView setVisibility visible");
        setVisibility(VISIBLE);
        initEmojiData();
    }

    /**
     * 初始化Emoji data
     */
    private void initEmojiData() {
        DLog.d("fLog", "mManager.getLoadEmojiFinish() ?" + mManager.getLoadEmojiFinish());
        if (mManager.getLoadEmojiFinish()) {//Emoji加载完成
            getEmojiPanel();
            setVisibility(View.VISIBLE);

            //进入就显示Emoji
            if (LocalStickerData.getInstance().getButtonPackages().size() != 0) {
                if (!isApply() || !mButtonAdapter.containsPkgName(mSelectPakName)) {
                    dealSelectEmojiTab(mButtonAdapter.getData().get(0).getPkgName(), true);
                } else {
                    dealSelectEmojiTab(mSelectPakName, true);
                }
            }
        } else {
            showWaitingDialog();
        }
    }

    /**
     * 检查Emoji Data是否加载完成
     */
    public void checkEmojiData() {//这个View可见才需要执行这些操作
        if (getVisibility() == VISIBLE) {
            mNeedRefresh = false;//已经刷新
            if (mManager.getLoadEmojiFinish()) {//Emoji加载完成
                mButtonAdapter.notifyDataSetChanged();
                refreshEmoji();
            } else {//显示的时候才需要显示WaitingDialog
                showWaitingDialog();
            }
        } else {
            mNeedRefresh = true;
        }
    }

    public void showWaitingDialog() {
        if (mWaitProgressDialog == null) {
            mDialogCount.incrementAndGet();
            final LoadingView v = (LoadingView) mActivity.getLayoutInflater().inflate(R.layout.loading_progress_view, null, false);
            v.setVisibility(View.VISIBLE);
            mWaitProgressDialog = new ProgressDialog(mActivity, ProgressDialog.THEME_TRADITIONAL);
            mWaitProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mWaitProgressDialog.setCancelable(false);
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.gravity = Gravity.CENTER;
            mWaitProgressDialog.show();
            mWaitProgressDialog.setContentView(v, lp);
            mWaitProgressDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    v.startLoading();
                }
            });
            mWaitProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    v.stopLoading();
                    if (mButtonAdapter == null) {
                        getEmojiPanel();
                        mButtonAdapter = new StickerButtonAdapter();
                        mButtonAdapter.setBgCheckDrawable(ComponentContext.getContext().getResources().getDrawable(R.drawable.sticker_btn_normal_bg), ComponentContext.getContext().getResources().getDrawable(R.drawable.sticker_btn_check_bg_white));
                        mButtonAdapter.setData(LocalStickerData.getInstance().getButtonPackages());
                        ItemClickSupport buttonItemClick = new ItemClickSupport(mStickerButtonList, mButtonAdapter);
                        buttonItemClick.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                            @Override
                            public void onItemClick(RecyclerView recyclerView, View view, int position, long id) {
                                if (view instanceof EmojiCheckableItem) {
                                    EmojiCheckableItem checkableItem = (EmojiCheckableItem) view;
                                    mStickerIndicatorView.moveToIndex(position);
                                    mButtonAdapter.setCheckedPosition(position, recyclerView);
                                    mStickerButtonList.smoothScrollToPosition(position);
                                    getEmojiPanel();
                                    //这种情况下直接选中不用刷新整个
                                    dealSelectEmojiTab(checkableItem.getPackageName(), false);
                                }
                            }
                        });
                        mButtonAdapter.setItemClickSupport(buttonItemClick);
                        mStickerButtonList.setAdapter(mButtonAdapter);

                        //进入就显示Emoji
                        if (LocalStickerData.getInstance().getButtonPackages().size() != 0) {
                            if (!isApply() || !mButtonAdapter.containsPkgName(mSelectPakName)) {
                                dealSelectEmojiTab(mButtonAdapter.getData().get(0).getPkgName(), true);
                            } else {
                                dealSelectEmojiTab(mSelectPakName, true);
                            }
                        }
                    } else {
                        mButtonAdapter.notifyDataSetChanged();
                        refreshEmoji();
                        //进入就显示Emoji
                        if (LocalStickerData.getInstance().getButtonPackages().size() != 0) {
                            if (!isApply() || !mButtonAdapter.containsPkgName(mSelectPakName)) {
                                dealSelectEmojiTab(mButtonAdapter.getData().get(0).getPkgName(), true);
                            } else {
                                dealSelectEmojiTab(mSelectPakName, true);
                            }
                        }
                    }
                }
            });
        } else {
            mDialogCount.incrementAndGet();
            mWaitProgressDialog.show();
        }
    }

    public void dismissWaitingDailog() {
        if (mWaitProgressDialog != null && mWaitProgressDialog.isShowing() && mDialogCount.decrementAndGet() == 0) {
            mWaitProgressDialog.dismiss();
        }
    }

    /**
     * 获取Emojipanel View
     *
     * @return
     */
    public View getEmojiPanel() {
        if (mEmojiPanelLayout == null) {
            mEmojiPanelLayout = this.findViewById(R.id.emoji_panel_stub);
            initEmojiPanel(mEmojiPanelLayout);
            if (mStickerViewListener != null && mEmojiPanelLayout.getVisibility() == VISIBLE) {
                mStickerViewListener.onStickerViewShow();
            }
        }
        return mEmojiPanelLayout;
    }
    /**
     * 初始化Emoji panel
     *
     * @param container
     */
    private void initEmojiPanel(View container) {
        if (mEmojiPager == null) {
            if (mStickerBackground != null) {
                RoundImageView blurBg = (RoundImageView) container.findViewById(R.id.sticker_panel_blur_bg);
                blurBg.setImageBitmap(mStickerBackground);
                mStickerIndicatorView.setBg(mStickerBackground);
            } else {
                container.findViewById(R.id.sticker_panel_blur_bg).setVisibility(GONE);
            }

            mEmojiPager = (ViewPager) container.findViewById(R.id.viewpager);
            mIndicatorLayout = (LinearLayout) container.findViewById(R.id.indicator_layout);
            mButtonAdapter = new StickerButtonAdapter();
            mButtonAdapter.setBgCheckDrawable(ComponentContext.getContext().getResources().getDrawable(R.drawable.sticker_btn_normal_bg), ComponentContext.getContext().getResources().getDrawable(R.drawable.sticker_btn_normal_bg));
            mButtonAdapter.setData(LocalStickerData.getInstance().getButtonPackages());
            ItemClickSupport buttonItemClick = new ItemClickSupport(mStickerButtonList, mButtonAdapter);
            buttonItemClick.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View view, int position, long id) {
                    if (view instanceof EmojiCheckableItem) {
                        EmojiCheckableItem checkableItem = (EmojiCheckableItem) view;
                        mButtonAdapter.setCheckedPosition(position, recyclerView);
                        mStickerIndicatorView.moveToIndex(position);
                        //mStickerButtonList.scrollToPosition(position);
                        getEmojiPanel();
                        //这种情况下直接选中不用刷新整个
                        dealSelectEmojiTab(checkableItem.getPackageName(), false);
                    }
                }
            });
            mButtonAdapter.setItemClickSupport(buttonItemClick);
            mStickerButtonList.setAdapter(mButtonAdapter);
            mEmojiPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    doPageSelect(arg0);
                    mLastPosition = arg0;
                    if (arg0 == mPageData.size() - 1) {
                        StatisticsUtils.statisticsStashClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_STASH_VALUE_EMOJI_DOWNLOAD_SHOW);
                    }
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {

                }
            });

            OnItemClickListener itemClick = new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    if (view instanceof EmojiItem) {
                        EmojiItem item = (EmojiItem) view;
                        EmojiBean bean = item.getItemData();

                        StickerApkResource apkResource = LocalStickerData.getInstance().getApkBean().get(bean.getPackageName());
                        if (apkResource != null && apkResource.canUse()) {
                            if (mStickerViewListener != null) {
                                mStickerViewListener.onStickerItemClick(bean);
                            }

                          /*  if (mEmojiPager.getCurrentItem() != 0 && (bean.isType(EmojiBean.TYPE_RESOURCE) || bean.isType(EmojiBean.TYPE_INSTALL_EMOJI_APK))) {

                                setEmojiItemData(LocalStickerData.getInstance().sortEmojiBean(mPageData.get(0).getEmojiBean(), bean));
                            }*/
                            if (mLastPosition > 12 && mLastPosition != mPageData.size() - 1) {
                                StatisticsUtils.statisticsStashClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_STASH_VALUE_DOWNLOAD_EMOJI__CLICK);
                            }
                        }
                    }
                }
            };

//            StickerGifBarView.OnGifItemClickListener onGIfItemClick = new StickerGifBarView.OnGifItemClickListener() {
//                @Override
//                public void onGifItemClick(String filePath) {
//                    if (mStickerViewListener != null) {
//                        mStickerViewListener.onGifClick(filePath);
//                    }
//                }
//            };

            mPageData = LocalStickerData.getInstance().getPageBeans(StickerConstant.isNewVersion(ComponentContext.getContext()), mIndexMap);
            LocalStickerData.getInstance().getEmojiData(mPageData.get(0));
            mPagerAdapter = new EmojiPageAdapter(getContext(), mPageData, itemClick, this);
            mPagerAdapter.setGifAutoScrollPosition(mGifAutoScrollPosition);
            mGifAutoScrollPosition = -1;
            mEmojiPager.setAdapter(mPagerAdapter);
        } else {//已经初始化过了  之需要将数据刷成正确的
            mButtonAdapter.setData(LocalStickerData.getInstance().getButtonPackages());
            mButtonAdapter.notifyDataSetChanged();
            int index = mEmojiPager.getCurrentItem();
            //当前选中的PKGName
            String pkgName = mPageData.get(index).getPkgName();
            int count = index - mIndexMap.get(pkgName).getIndex();
            mPageData = LocalStickerData.getInstance().getPageBeans(StickerConstant.isNewVersion(ComponentContext.getContext()), mIndexMap);
            mEmojiPager.setAdapter(null);
            mPagerAdapter.setData(mPageData);
            mPagerAdapter.setGifAutoScrollPosition(mGifAutoScrollPosition);
            mGifAutoScrollPosition = -1;
            mEmojiPager.setAdapter(mPagerAdapter);

            PagePositionBean pageBean = mIndexMap.get(pkgName);
            if (pageBean != null) {
                int tap = pageBean.getIndex() + count;
                autoSelectEmojiTab(pkgName, tap);
            } else {
                String newPkgName = InsideStickerTool.STICKER_PKG_NAME_EMOJI;
                PagePositionBean page = mIndexMap.get(pkgName);
                if (page == null) {
                    Set<String> stringSet = mIndexMap.keySet();
                    for (String key : stringSet) {
                        page = mIndexMap.get(key);
                        newPkgName = key;
                        break;
                    }
                    if (page != null) {
                        autoSelectEmojiTab(newPkgName, 0);
                    }
                } else {
                    autoSelectEmojiTab(newPkgName, 0);
                }
            }
        }
    }

    public void reloadData() {
        if (mEmojiPanelLayout != null) {
            String lastSelectPkgName = mButtonAdapter.getLastSelectPkgName();
            mButtonAdapter.setData(LocalStickerData.getInstance().getButtonPackages());
            mPageData = LocalStickerData.getInstance().getPageBeans(StickerConstant.isNewVersion(ComponentContext.getContext()), mIndexMap);
            mEmojiPager.setAdapter(null);
            mPagerAdapter.setData(mPageData);
            mPagerAdapter.setGifAutoScrollPosition(mGifAutoScrollPosition);
            mGifAutoScrollPosition = -1;
            mEmojiPager.setAdapter(mPagerAdapter);
            if (!isApply() || !mButtonAdapter.containsPkgName(mSelectPakName)) {
                if (!TextUtils.isEmpty(lastSelectPkgName)) {
                    dealSelectEmojiTab(lastSelectPkgName, true);
                } else {
                    dealSelectEmojiTab(mButtonAdapter.getData().get(0).getPkgName(), true);
                }
            } else {
                dealSelectEmojiTab(mSelectPakName, true);
            }

        } else {
            initEmojiData();
        }
    }

    private String mGifTitle = "";

    public void setGifTitle(String gifTitle) {
        mGifTitle = gifTitle;
    }

    private String mSelectPakName = "";

    public void setSelectPakName(String selectPakName) {
        mSelectPakName = selectPakName;
    }

    /**
     * 接收到安装或者卸载掉 EMoji插件的广播时做处理
     */
    public void refreshEmoji() {
        if (mFinishInflate) {//这个是刷新最近使用的Emoji列表
            setEmojiItemData(true);
        }
        if (mEmojiPanelLayout != null) {
            initEmojiPanel(mEmojiPanelLayout);
        }
    }


    /**
     * 刷新Emojiitem
     *
     * @param isChange
     */
    private void setEmojiItemData(boolean isChange) {
        if (isChange) {
            mPagerAdapter.refresh(0);
        }
    }

    /**
     * 设置EmojiPanel的可见性
     * 带有动画
     *
     * @param visible
     */
    public void setEmojiPanelVisible(boolean visible, boolean animation) {
        if (visible) {
            View v = getEmojiPanel();
            if (v.getVisibility() != View.VISIBLE) {
                if (mEmojiPanelIn == null) {
                    mEmojiPanelIn = AnimationUtils.loadAnimation(getContext(), R.anim.bottom_in);
                    mEmojiPanelIn.setDuration(250);
                }
                if (animation) {
                    v.startAnimation(mEmojiPanelIn);
                }
                if (mStickerViewListener != null) {
                    mStickerViewListener.onStickerViewShow();
                }
                v.setVisibility(View.VISIBLE);
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mStickerIndicatorView.setVisibility(VISIBLE);
                    }
                }, 220);
            }
        } else {
            final View v = getEmojiPanel();
            if (v.getVisibility() == View.VISIBLE) {
                if (mEmojiPager.getCurrentItem() == 0) {
//                    if (mEmojiPager.getChildAt(0) instanceof StickerGifBarView) {
//                        ((StickerGifBarView) mEmojiPager.getChildAt(0)).hideKeyBoard();
//                    }
                }
                if (mEmojiPanelOut == null) {
                    mEmojiPanelOut = AnimationUtils.loadAnimation(getContext(), R.anim.bottom_out);
                    mEmojiPanelOut.setDuration(250);
                    mEmojiPanelOut.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            if (mStickerViewListener != null) {
                                mStickerViewListener.onStickerViewHide();
                            }
                            v.setVisibility(View.GONE);
                            mStickerIndicatorView.setVisibility(GONE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                }
                if (animation) {
                    v.startAnimation(mEmojiPanelOut);
                }
            }
        }
    }

    /**
     * 获取mEmojiPanelLayout 用于判断是否需要执行动画或者其他
     * 不需要为空时执行初始化
     *
     * @return
     */
    public View getEmojiPanelButNotInit() {
        return mEmojiPanelLayout;
    }


    private void doPageSelect(int position) {
        if (position == 0) {
            mIndicatorLayout.setVisibility(VISIBLE);
            checkListButton(mPageData.get(position).getPkgName());
        } else if (position > 0) {
            mIndicatorLayout.setVisibility(VISIBLE);
            if (mLastPosition >= 0) {
                if (mLastPosition >= mPageData.size()) {
                    EmojiPageBean pageBean = mPageData.get(position);
                    String pkgName = pageBean.getPkgName();
                    int index = position - mIndexMap.get(pageBean.getPkgName()).getIndex();
                    selectTab(pkgName, index, true);
                } else {
                    EmojiPageBean lastPageBean = mPageData.get(mLastPosition);
                    EmojiPageBean pageBean = mPageData.get(position);
                    if (mIndexMap.get(lastPageBean.getPkgName()).getIndex() == mIndexMap.get(pageBean.getPkgName()).getIndex()) {
                        changeIndicator(position - mIndexMap.get(pageBean.getPkgName()).getIndex());//指示器更新
                    } else {//需要切换Tab
                        String pkgName = pageBean.getPkgName();
                        int index = position - mIndexMap.get(pageBean.getPkgName()).getIndex();
                        selectTab(pkgName, index, true);
                    }
                }
            } else {
                EmojiPageBean pageBean = mPageData.get(position);
                changeIndicator(position - mIndexMap.get(pageBean.getPkgName()).getIndex());//指示器更新
            }
        }
    }

    /**
     * 改变指示器的状态
     */
    private void changeIndicator(int page) {
        if (!isLineIndicator) {
            int len = mIndicatorLayout.getChildCount();
            String pkgName = mPageData.get(mEmojiPager.getCurrentItem()).getPkgName();
            boolean flag = pkgName.equals(StickerConstant.APK_EMOJI_PKG_NAME) || pkgName.equals(mActivity.getPackageName());
            for (int i = 0; i < len; i++) {
                if (i == page) {
                    if (flag && i == 0) {
                        ((ImageView) mIndicatorLayout.getChildAt(i)).setImageResource(R.drawable.ic_stash_emoji_indicator_recent_on);
                    } else {
                        ((ImageView) mIndicatorLayout.getChildAt(i)).setImageResource(R.drawable.ic_stash_emoji_indicator_current_on);
                    }
                } else {
                    if (flag && i == 0) {
                        ((ImageView) mIndicatorLayout.getChildAt(i)).setImageResource(R.drawable.ic_stash_emoji_indicator_recent_off);
                    } else {
                        ((ImageView) mIndicatorLayout.getChildAt(i)).setImageResource(R.drawable.ic_stash_emoji_indicator_current_off);
                    }
                }
            }
        } else {
            LineIndicator lineIndicator = (LineIndicator) mIndicatorLayout.getChildAt(0);
            lineIndicator.moveTo(page);
        }
    }

    /**
     * 点击按钮时切换到合适位置  会让Emoji Pannel显示
     *
     * @param pkgName
     */
    public void dealSelectEmojiTab(String pkgName, boolean isNeedCheck) {
        selectTab(pkgName, 0, isNeedCheck);
        setEmojiPanelVisible(true, true);
        //默认选中第一个
        PagePositionBean bean = mIndexMap.get(pkgName);
        if (bean == null) {
            return;
        }
        int index = bean.getIndex();
        int offset = 0;
        if (mStickerAutoScrollPosition != -1) {
            offset = mStickerAutoScrollPosition / 8;
            if (offset + 1 > bean.getPageNum()) {
                offset = 0;
            }
            mStickerAutoScrollPosition = -1;
        }
        mEmojiPager.setCurrentItem(index + offset, false);
        //应用
        if (isApply()) {
            mSelectPakName = "";
        }

        if (InsideStickerTool.STICKER_PKG_NAME_GIF.equals(pkgName) && !TextUtils.isEmpty(mGifTitle)) {
            mEmojiPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    View childAt = mEmojiPager.getChildAt(0);
//                    if (childAt != null && childAt instanceof StickerGifBarView) {
//                        ((StickerGifBarView) childAt).preSearch(mGifTitle);
//                    }
                    mGifTitle = "";
                }
            }, 250);
        }

    }

    /**
     * 选中需要选中的
     *
     * @param pkgName
     */
    public void checkListButton(final String pkgName) {
        if (mStickerButtonList == null) {
            return;
        }
        mStickerButtonList.post(new Runnable() {//post防止选中没有移动
            @Override
            public void run() {
                int position = mButtonAdapter.setCheckedPosition(pkgName);
                if (position != -1) {
                    mStickerButtonList.smoothScrollToPosition(position);
                    mStickerIndicatorView.moveToIndex(position);
                }
            }
        });
    }

    /**
     * 下载或者安装完成后的处理  不修改Emoji Pannel的状态
     *
     * @param pkgName
     * @param position
     */
    private void autoSelectEmojiTab(String pkgName, int position) {
        selectTab(pkgName, position - mIndexMap.get(pkgName).getIndex(), true);
        mEmojiPager.setCurrentItem(position, false);
    }

    /**
     * 这个方法会重新生成 mIndicatorLayout的指示器
     *
     * @param pkgName
     * @param index
     */
    private void selectTab(String pkgName, int index, boolean isNeedCheck) {
        if (isNeedCheck) {
            checkListButton(pkgName);
        }
        if (InsideStickerTool.STICKER_PKG_NAME_GIF.equals(pkgName)) {
            mIndicatorLayout.setVisibility(GONE);
        } else {
            mIndicatorLayout.setVisibility(VISIBLE);

            int count = 0;
            if (mIndexMap != null && mIndexMap.get(pkgName) != null) {
                count = mIndexMap.get(pkgName).getPageNum();
            } else {
                return;
            }

            //重新声场指示器
            mIndicatorLayout.removeAllViews();

            //只有APK_EMOJI_PKG_NAME 和 内置的才有最近的列表
            boolean flag = pkgName.equals(StickerConstant.APK_EMOJI_PKG_NAME) || pkgName.equals(mActivity.getPackageName());

            if (count == 1) {//存在Extra emoji
                //do nothing
            } else if (count < 20) {//page == 1需要变成两页 有一页是引导
                isLineIndicator = false;
                int right = getResources().getDimensionPixelSize(R.dimen.image_edit_emoji_indicator_margin);
                for (int i = 0; i < count; i++) {
                    if (i != count - 1) {
                        ImageView iv = new ImageView(getContext());
                        iv.setScaleType(ScaleType.CENTER);

                        if (i == index) {
                            if (flag && i == 0) {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_recent_on);
                            } else {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_current_on);
                            }
                        } else {
                            if (flag && i == 0) {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_recent_off);
                            } else {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_current_off);
                            }
                        }

                        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        lp.rightMargin = right;
                        mIndicatorLayout.addView(iv, lp);
                    } else {
                        ImageView iv = new ImageView(getContext());
                        iv.setScaleType(ScaleType.CENTER);
                        if (i == index) {
                            if (flag && i == 0) {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_recent_on);
                            } else {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_current_on);
                            }
                        } else {
                            if (flag && i == 0) {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_recent_off);
                            } else {
                                iv.setImageResource(R.drawable.ic_stash_emoji_indicator_current_off);
                            }
                        }
                        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        mIndicatorLayout.addView(iv, lp);
                    }
                }
                mIndicatorLayout.setOnTouchListener(new OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        return true;
                    }
                });
            } else {
                isLineIndicator = true;
                //直线
                mIndicator = new LineIndicator(getContext());
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                lp.width = DeviceUtils.getScreenWidthPx(ComponentContext.getContext()) - DeviceUtils.dip2px(ComponentContext.getContext(), 40f);
                mIndicator.setLayoutParams(lp);
                mIndicator.setCurrentPage(index);
                mIndicator.setPageCount(count);
                mIndicator.setPkgName(pkgName);
                mIndicator.setOnPageChangeListener(new LineIndicator.OnPageChangeListener() {
                    @Override
                    public void onPageChange(int page) {
                        mEmojiPager.setCurrentItem(mIndexMap.get(mIndicator.getPkgName()).getIndex() + page);
                    }
                });
                mIndicatorLayout.addView(mIndicator);
                mIndicatorLayout.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        return mIndicator.onTouchEvent(event);
                    }
                });
            }
        }
    }

    /**
     * 将所有的Tab都取消选中
     */
    public void restore(boolean moveToFirst) {
        if (mButtonAdapter != null) {
            mButtonAdapter.setCheckedPosition(-1, mStickerButtonList);
            if (moveToFirst) {
                mStickerButtonList.scrollToPosition(0);
                mStickerIndicatorView.moveToIndex(0);
            }
        }
    }

    /**
     * 购买的Dialog
     */
    public void showConfirmPayDialog() {
        if (mConfirmDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle(R.string.tip);
            builder.setMessage(R.string.store_sticker_purchase_tip);
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmDialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmDialog.dismiss();
                }
            });
            mConfirmDialog = builder.create();
            mConfirmDialog.setCancelable(true);
            mConfirmDialog.setCanceledOnTouchOutside(false);
            mConfirmDialog.show();
        } else {
            mConfirmDialog.show();
        }
    }

    public void setManager(StickerManager manager) {
        mManager = manager;
    }

    public void setStickerViewListener(StickerView.StickerViewListener stickerViewListener) {
        mStickerViewListener = stickerViewListener;
    }

    @Override
    public boolean isApply() {
        return !TextUtils.isEmpty(mSelectPakName);
    }

    public void setGifAutoScrollPosition(int gifAutoScrollPosition) {
        mGifAutoScrollPosition = gifAutoScrollPosition;
    }

    public void setStickerAutoScrollPosition(int stickerAutoScrollPosition) {
        mStickerAutoScrollPosition = stickerAutoScrollPosition;
    }
}
